
// 载入所有的页面视图 组件
import Home from "./views/Home.vue.js" //首页
import Task from "./views/Task.vue.js" //任务详情
import About from "./views/About.vue.js" //关于项目
import History from "./views/History.vue.js" //历史上的今天
import Login from "./views/Login.vue.js" //登录
//const About = {template: '<div>About this page</div>',}
//import { createApp } from 'vue';
import TaskList from './components/TaskList.vue.js'; //任务列表

import { getVersion } from './api.js';

import { checkActiveTime, validateToken } from './utils/auth.js'; // 导入函数

const app = Vue.createApp({
  data(){
    return{
      version: "v0.0.0",
      timestamp: new Date(), //vm.timestamp

      topMenu:[
        {path:'/', caption:'Home'},
        {path:'/tasks/?next_period=uncompleted', caption:'uncompleted'},
        {path:'/history', caption:'history'},
        {path:'/about', caption:'about'},
        {path:'/login', caption:'login'},
      ],
    }
  },

  computed:{
    currentRoute(){
      return this.$route.path;
    },

    elapse(){ // 自博客创建以来的天数，保留3位小数
      return ((this.timestamp.getTime() - 1719564446600)/1000/3600/24).toFixed(3);
    }
  },


  //全局判断上次活跃超过5个小时则自动退出: 活动事件
  created() {
    this.updateLastActiveTime();
    window.addEventListener('mousemove', this.updateLastActiveTime);
    window.addEventListener('keydown', this.updateLastActiveTime);
  },

  beforeUnmount() {
    window.removeEventListener('mousemove', this.updateLastActiveTime);
    window.removeEventListener('keydown', this.updateLastActiveTime);
  },



  methods: {
    //全局判断上次活跃超过5个小时则自动退出：更新时间戳
    updateLastActiveTime() {
      this.checkActive();
      localStorage.setItem('lastActive', Date.now());
    },

    checkActive(){
      if(!checkActiveTime()){
        alert("超时退出")
        this.logout(); // 超过 5 小时，执行退出操作
      }
    },
    
    // 退出
    logout() {
      this.$router.push('/login'); // 重定向到登录页面
    },



    async fetchVersion() {
      // 使用 Axios 获取任务
      axios.get( getVersion() )
        .then(response => {
          this.version = response.data;
          document.title += " " + this.version
          //console.log(">> >>", response.data)
          window.version = this.version; // 这个变量不知道怎么传递给路由后的about页
        })
        .catch(error => {
          console.error('Error fetching tasks:', error);
        });
    },

  },

  async mounted() {
    this.fetchVersion(); //获取版本号

    const token = localStorage.getItem('token');
    const user_id = localStorage.getItem('user_id');
    if (token && user_id) {
      const isValid = await validateToken(token, user_id);

      if (!isValid) {
        this.logout(); // 如果无效，执行退出操作
      }

      this.checkActive(); // 只有在登录时检查活跃状态
    }
  },

});




//路由表
const routes = [
  { path: '/', component: Home },
  { path: '/tasks', component: TaskList },
  //{ path: '/tasks/:last_period', component: TaskList },
  { path: '/tasks/:task_id', component: Task },
  { path: '/history', component: History },
  { path: '/about', component: About },
  { path: '/login', component: Login },
]

// 路由
const router = VueRouter.createRouter({
	//mode: 'history',
  history: VueRouter.createWebHashHistory(), 
  routes,
})




// 全局导航守卫
router.beforeEach( async (to, from, next) => {
  const token = localStorage.getItem('token');
  const user_id = localStorage.getItem('user_id');


  // 如果未登录，不再检查是否超时
  if (!token) {
      if (to.path !== '/login') {
          next('/login'); // 未登录时重定向到登录页面
      } else {
          next(); // 允许访问登录页面
      }
  } else {
      // 如果已登录，检查活跃状态
      // 如果已登录，验证 token 和 uid
      const isValid = await validateToken(token, user_id);
      if(!isValid){
        // 如果无效，执行退出操作
        console.log("Token 无效，正在清理")
        localStorage.removeItem('token');
        localStorage.removeItem('uid');
        localStorage.removeItem('username');
      }
      if (!checkActiveTime()) {
          next('/login'); // 超时，重定向到登录页面
      } else {
          next(); // 继续导航
      }
  }

});




app.use(router)
var vm=app.mount("#app");
window.vm=vm
